package com.heima.user.service.impl;

import com.heima.common.exception.CustException;
import com.heima.constants.message.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    //关注或者取消关注
    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        //非空判断
        if (dto == null || dto.getAuthorApUserId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null || user.getId() == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取登录用户的id和关注的id
        String authorId = dto.getAuthorApUserId().toString();
        String loginId = user.getId().toString();
        //判断关注的id和登录id是否相同
        if (loginId == authorId) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不可以关注自己!");
        }
        //判断是否已经关注该用户,从redis中拿数据
        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginId, authorId);
        //判断操作类型
        if (dto.getOperation() == 0) {
            //关注用户,判断是否已经关注
            if (score != null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "您已经关注该用户!");
            }
            //用户关注作者
            redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST +
                    loginId, authorId, System.currentTimeMillis());
            //作者关注用户
            redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + authorId, loginId, System.currentTimeMillis());
        }
        if (dto.getOperation() == 1) {
            //关注用户,判断是否已经关注
            if (score == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "您还未关注该用户,无法取消关注!");
            }
            //用户取消关注作者
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST+loginId, authorId);
            //作者取消关注用户
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorId, loginId);
        }
        return ResponseResult.okResult();
    }
}
